package com.wzqj.agent.web.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.common.ConfigHelper;
import com.wzqj.agent.common.Log;
import com.wzqj.agent.common.SoaConfig;
import com.wzqj.agent.common.exception.BusinessErrorType;
import com.wzqj.agent.common.exception.BusinessException;
import com.wzqj.agent.web.dao.MerchantStoreDao;
import com.wzqj.agent.web.domain.MerchantStore;
import com.wzqj.agent.web.service.StoreService;
import com.wzqj.wsp.comm.Const;
import com.wzqj.wsp.response.ResponseValue;
import com.wzqj.wsp.response.ResultStatus;
import com.wzqj.wsp.soa.SOAUtil;
@Service("StoreService")
public class StoreServiceImpl implements StoreService{

	/**
	 * 阿里云存储服务
	 */
	private static final String ALIYUN_URL = ConfigHelper.getProperty("ALIYUN_URL");
	/**
     * 商户平台服务
     */
    private static final String WMP_PROVIDER_APP_CODE = ConfigHelper.getProperty("WMP_PROVIDER_APP_CODE");
    /**
     * 用户店铺列表
     */
    private static final String WMP_USER_STORES_URL = "merchant/getUserMerchantByWhere";
    /**
     * 搜索 店铺
     */
    private static final String WMP_MERCHANT_SEARCH = "merchant/getMerchantBySearch";
    
    /**
     * 校验持否为店铺mcode
     */
    private static final String WMP_CHECK_MCODE = "merchant/checkIsMcode";
    /**
     * 绑定店铺到商户
     */
    private static final String WMP_MERCHANT_STORE_BIND_URL = "merchant/bindUserMerchant";
    
	/**
	 * 运营支撑平台服务
	 */
	private static final String ACC_PROVIDER_APP_CODE = ConfigHelper.getProperty("ACC_PROVIDER_APP_CODE");

	/**
     * 添加店铺
     */
    private static final String ACC_MERCHANT_STORE_ADD = "merchant/apply";
    /**
     * 修改店铺
     */
    private static final String ACC_MERCHANT_STORE_UPDATE = "merchant/update";
	/**
	 * 店铺详情
	 */
	private static final String ACC_USER_STORE_LIST = "merchant/list";
	 /**
     * 店铺下设备数量
     */
    private static final String ACC_MERCHANT_STORE_COUNT = "devices/getCountByMcodes";
    
    /**
     * 店铺下设备信息
     */
    private static final String ACC_STORE_DEVICE = "devices/listByStoreIds";

    /**
     * 行业列表（新）
     */
    private static final String ACC_BIZ_CLASSIFY_NEW = "bizclassify/listLevelClassify";
    /**
     * 来源于代理商平台
     */
    private static final int source_agent = 2;
    
    @Autowired
    private MerchantStoreDao merchantStoreDao;
	/**
	 * 根据店铺id获取店铺详情，长沙接口
	 * 
	 * @param storeid
	 * @return
	 */
    @Override
	public JSONObject getStoreByStoreId(String storeId) {

		JSONObject soaParam = SoaConfig.getSoaParam();
		JSONObject params = new JSONObject();
		params.put("storeIds", storeId);
		//调取运营支撑平台店铺详情接口
		ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE,ACC_USER_STORE_LIST, params, soaParam);
		if (res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS) {
			JSONArray data = (JSONArray) res.getData();
			JSONObject store = data.getJSONObject(0);
			String busiLicense = store.getString("busiLicense");//营业执照
			String busiImgs = store.getString("busiImgs");//门店照片
			List<String> busiImgsList = new ArrayList<String>();
			if (!StringUtils.isEmpty(busiImgs)) {
				String[] imgs = busiImgs.split(",");
				for (String img : imgs) {
					StringBuffer sb = new StringBuffer();
					sb.append(ALIYUN_URL).append(img);
					busiImgsList.add(sb.toString());
					//sb.append(ALIYUN_URL).append(img).append(",");
				}
			}
			store.put("busiLicense", StringUtils.isEmpty(busiLicense) ? ""
					: ALIYUN_URL + busiLicense);
			//store.put("busiLicense",busiLicense);
			store.put("busiImgs", busiImgsList);
			JSONArray posList = getDevicesByStoreIds(storeId);
			if (posList != null) {
				store.put("posList", posList);
				store.put("posListSize", posList.size());
			}
			
			//处理行业信息格式不统一问题
            String bizClassify = store.getString("bizClassify");
            if (!StringUtils.isEmpty(bizClassify)) {
            	//校验bizClassify为jsonArray格式还是jsonObject格式
            	char[] strChar = bizClassify.substring(0, 1).toCharArray(); 
                char firstChar = strChar[0]; 
                if (firstChar== '{') {
					JSONObject bizClassifyJO = JSONObject.parseObject(bizClassify);
					JSONArray bizClassifyJA = new JSONArray();
					bizClassifyJA.add(bizClassifyJO);
					store.put("bizClassify", bizClassifyJA);
				}
			}
            
            
			return store;
		}
		return null;
	}

	/**
	 * 根据店铺获取设备信息
	 * @param storeIds
	 * @return
	 */
    @Override
	public JSONArray getDevicesByStoreIds(String storeIds) {
		JSONObject devices = null;
		JSONObject soaParam = SoaConfig.getSoaParam();
		JSONObject params = new JSONObject();
		params.put("storeIds", storeIds);
		ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE,
				ACC_STORE_DEVICE, params, soaParam);
		if (res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS) {
			JSONArray data = (JSONArray) res.getData();
			devices = data.getJSONObject(0);
			JSONArray posList = devices.getJSONArray("posLst");
			return posList;
		}
		return null;
	}
	/**
     * 获取门店绑定pos数量
     * @param mcode
     * @return
     */
    @Override
    public int getStoreCount(String mcode) {

        int count = 0;
        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("mcodes",mcode);
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_MERCHANT_STORE_COUNT, params,soaParam);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            JSONArray data = (JSONArray) res.getData();
            count = data.getJSONObject(0).getIntValue("deviceCount");
        }
        return count;
    }
    @Override
    public String doSearch(String shopName,String city,String lastId,int pageIndex,int limit) {
		
		ResponseValue rv = new ResponseValue();
		JSONObject soaParam = SoaConfig.getSoaParam();
		
		boolean isMcodeOrShopname = false;
		JSONObject params = new JSONObject();

		Pattern pattern = Pattern.compile("[0-9]*");
		// 判断数字的长度，判断是不是mcode
		int mcodeLen = shopName.length();
		boolean isMcode = pattern.matcher(shopName).matches();
		if (isMcode && mcodeLen == 6) {// 判断是不是mcode
			JSONObject paramsMcode = new JSONObject();
			paramsMcode.put("mcode", shopName);
			ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE,WMP_CHECK_MCODE, paramsMcode, soaParam);
			if (res.getStatus() == ResultStatus.SUCCESS_STATUS) {

				JSONArray obj = (JSONArray) res.getData();
				Log.run.info("门店数量为：" + obj.size());
				if (obj.size() > 0) {// 是mcode
					isMcodeOrShopname = true;
				}
			}
		}
		if (isMcodeOrShopname) {// 是mcode
			params.put("mcode", shopName);
			params.put("searchMerByMcode", true);
			rv = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE,WMP_USER_STORES_URL, params, soaParam);
			rv.setInfo("mcode");
		} else {// 其他情况
			params.clear();
			params.put("shopName", shopName);
			params.put("city", city);
			params.put("lastId", lastId);
			params.put("pageIndex", pageIndex);
			params.put("limit", limit);
			rv = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE,WMP_MERCHANT_SEARCH, params, soaParam);
		}
		
		return rv.toString();
	}
    
    /**
     * 获取行业列表(新)
     */
    @Override
    public JSONArray getBizClassifyList() {
        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_BIZ_CLASSIFY_NEW, params, soaParam);
        System.out.println("-------getBizClassifyList:"+res.toString());
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            return (JSONArray) res.getData();
        }
        return null;
    }
    /**
     * 绑定店铺到商户
     */
    @Override
    public JSONObject bind(String qualificationId,String storeId,String mcode,String claimStatus){
    	JSONObject soaParam = SoaConfig.getSoaParam();
    	//ResponseValue rv = new ResponseValue();
		//try{
			if(qualificationId != null && !qualificationId.equals("")&&storeId!=null&&!storeId.equals("")&&mcode!=null&&!mcode.equals("")){
				JSONObject params = new JSONObject();
				params.put("storeId", storeId);
				params.put("mcode", mcode);
				params.put("qualificationId", qualificationId);
					
				params.put("claimStatus",claimStatus);
				ResponseValue res = SOAUtil.getResValFromSOA(WMP_PROVIDER_APP_CODE, WMP_MERCHANT_STORE_BIND_URL, params,soaParam);
				if (res != null){
					if(res.getStatus() == ResultStatus.SUCCESS_STATUS){
						//存储商户认领店铺关系
						MerchantStore merchantStore = new MerchantStore();
				        merchantStore.setMcode(mcode);
				        merchantStore.setStoreId(storeId);
				        merchantStore.setMerId(qualificationId);
				        merchantStore.setSource(source_agent);
				        merchantStoreDao.insert(merchantStore);
				        JSONObject data = new JSONObject();
				        data.put("mcode",mcode);
				        //rv.setData(data);
				        return data;
				    }else {
				    	throw BusinessException.createInstance(BusinessErrorType.MERCHANT_STORE_BIND_ERROR);
				    }
				 }else{
				 	throw BusinessException.createInstance(BusinessErrorType.MERCHANT_STORE_BIND_ERROR);
				 }
			/*}else{
				rv.setFlag(false);
				rv.setInfo("资质未提交或未审核通过，无法领取门店");
			 */
			}
			
		/*}catch(Exception e){
			//rv.setErrMsg(e.getMessage());
			Log.run.error(e.getMessage());
		}
		*/
		//return rv.toString();
			return null;
    }
    
    /**
     * 添加店铺
     * @param store
     * @return
     */
    @Override
    public JSONObject addStore(JSONObject store) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("data", store);
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE,ACC_MERCHANT_STORE_ADD,params,soaParam);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            return (JSONObject) res.getData();
        }
        return null;
    }
    
    
    /**
     * 更新店铺信息
     * @param store
     * @param storeId
     * @return
     */
    @Override
    public JSONObject updateStore(JSONObject store, String storeId) {

        JSONObject soaParam = SoaConfig.getSoaParam();
        JSONObject params = new JSONObject();
        params.put("data", store);
        params.put("storeId",storeId);
        ResponseValue res = SOAUtil.getResValFromSOA(ACC_PROVIDER_APP_CODE, ACC_MERCHANT_STORE_UPDATE, params, soaParam);
        if(res != null && res.getStatus() == ResultStatus.SUCCESS_STATUS){
            return (JSONObject) res.getData();
        }
        return null;
    }
}
